/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package UI;

import Gmail.NhanEmail;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeBodyPart;
import java.io.*;
import java.security.Key;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.swing.JFileChooser;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author Envy
 */
public class ManHinhChinh extends javax.swing.JFrame {

    /**
     * Creates new form ManHinhChinh
     */
    public ManHinhChinh() {
        initComponents();
        jScrollPane1.setVisible(true);
        jPanel2.setVisible(false);
        try {
            LoadInbox();
        } catch (IOException ex) {
            Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
        }
        btnRead.setText("INBOX" + " (" + totalMessages + ")");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        labelNguoiGui = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        labelTieuDe = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtFileName = new javax.swing.JLabel();
        labelSave = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtNoiDung = new javax.swing.JTextArea();
        jLabel5 = new javax.swing.JLabel();
        labelNgayGui = new javax.swing.JLabel();
        btnGiaiMa = new javax.swing.JButton();
        btnRead = new javax.swing.JButton();
        btnSoanEmail = new javax.swing.JButton();
        labelForward = new javax.swing.JLabel();
        labelBack = new javax.swing.JLabel();
        btnRefresh = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        itemThoat = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        itemDelete = new javax.swing.JMenuItem();
        itemClientRow = new javax.swing.JMenuItem();

        jLabel1.setText("jLabel1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Hộp thư");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getAccessibleContext().setAccessibleName("");

        jLabel2.setText("Người gửi:");

        labelNguoiGui.setText("labelNguoiGui");

        jLabel4.setText("Tiêu đề:");

        labelTieuDe.setText("labelTieuDe");

        jLabel6.setText("Nội dung:");

        txtFileName.setText("txtFileName");

        labelSave.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        labelSave.setForeground(new java.awt.Color(102, 102, 255));
        labelSave.setText("Save");
        labelSave.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        labelSave.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                labelSaveMouseClicked(evt);
            }
        });

        txtNoiDung.setColumns(20);
        txtNoiDung.setLineWrap(true);
        txtNoiDung.setRows(5);
        jScrollPane2.setViewportView(txtNoiDung);

        jLabel5.setText("Ngày gửi");

        labelNgayGui.setText("labelTieuDe");

        btnGiaiMa.setText("Giải mã");
        btnGiaiMa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGiaiMaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 623, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(labelSave)
                            .addComponent(txtFileName)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel5))
                                .addGap(26, 26, 26)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(labelNgayGui)
                                    .addComponent(labelTieuDe)
                                    .addComponent(labelNguoiGui))))
                        .addContainerGap(41, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnGiaiMa)
                        .addGap(129, 129, 129))))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(labelNguoiGui))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(labelTieuDe))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(labelNgayGui))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel6))
                    .addComponent(btnGiaiMa))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(txtFileName)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(labelSave)
                .addGap(18, 18, 18))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 682, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 447, Short.MAX_VALUE))
        );

        btnRead.setText("INBOX");
        btnRead.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnReadActionPerformed(evt);
            }
        });

        btnSoanEmail.setText("COMPOSE");
        btnSoanEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSoanEmailActionPerformed(evt);
            }
        });

        labelForward.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Other/icon/1371387552_7.png"))); // NOI18N
        labelForward.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        labelForward.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                labelForwardMouseClicked(evt);
            }
        });

        labelBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Other/icon/1371387531_8.png"))); // NOI18N
        labelBack.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        labelBack.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                labelBackMouseClicked(evt);
            }
        });

        btnRefresh.setText("REFRESH");
        btnRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefreshActionPerformed(evt);
            }
        });

        jMenu1.setText("File");

        itemThoat.setText("Logout");
        itemThoat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemThoatActionPerformed(evt);
            }
        });
        jMenu1.add(itemThoat);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");

        itemDelete.setText("Delete Server SelectedRow");
        itemDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemDeleteActionPerformed(evt);
            }
        });
        jMenu2.add(itemDelete);

        itemClientRow.setText("Delete Client SelectedRow");
        itemClientRow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemClientRowActionPerformed(evt);
            }
        });
        jMenu2.add(itemClientRow);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(labelBack)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelForward)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnSoanEmail, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnRead, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnRefresh, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(labelBack)
                    .addComponent(labelForward))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnRefresh)
                        .addGap(16, 16, 16)
                        .addComponent(btnRead)
                        .addGap(18, 18, 18)
                        .addComponent(btnSoanEmail)
                        .addContainerGap())
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private String receivingHost;
    private static int totalMessages = 0,
            newMessages = 0;

//    public void readGmail() {
//        //Login login=new Login();
//
//
//        /*
//         * this will print subject of all messages in the inbox of
//         * sender@gmail.com
//         */
//        this.receivingHost = "imap.gmail.com";//for imap protocol
//        //Properties props2=System.getProperties();
//        Login.props.setProperty(
//                "mail.store.protocol", "imaps");
//        // I used imaps protocol here
//
//        //Session session2=Session.getDefaultInstance(props2, null);
//
//        try {
//
//            Store store = Login.session1.getStore("imaps");
//
//            store.connect(this.receivingHost, "", "");
//
//            Folder inbox = store.getFolder("INBOX");//get inbox
//
//            //                   folder.open(Folder.READ_ONLY);//open folder only to read
//
//            Message[] messages = inbox.getMessages();
//            totalMessages = inbox.getMessageCount();
//            newMessages = inbox.getNewMessageCount();
//            DefaultTableModel dtm = new DefaultTableModel();
//            dtm.addColumn("Subject");
//            dtm.setNumRows(messages.length);
//            for (int i = 0; i < messages.length; i++) {
//
//                //print subjects of all mails in the inbox
//                dtm.setValueAt(messages[i].getSubject(), i, 1);
//                //dtm.set
//                //dtm.
//                System.out.println(messages[i].getSubject());
//
//                //anything else you want
//
//            }
//
//
//            //Hiển thị lên Table
//            jTable1.setModel(dtm);
//            jTable1.setEnabled(true);
//            //close connections
//
//            inbox.close(true);
//
//            store.close();
//
//
//        } catch (Exception e) {
//
//            System.out.println(e.toString());
//
//
//        }
//    }
    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1MouseClicked

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        // TODO add your handling code here:
//        NhanEmail nhan = new NhanEmail();
//        nhan.readGmail(Login.user, Login.pass, jTable1);
//
//
//        jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
//
//            public void valueChanged(ListSelectionEvent event) {
//                // do some actions here, for example
//                // print first column value from selected row
//                jScrollPane1.setVisible(false);
//                jPanel2.setVisible(true);
//                
//                int rIndex = jTable1.getSelectedRow();
//                
//                //labelNguoiGui.setText(jTable1.findComponentAt(x, 0).getName());
//                
//                labelNguoiGui.setText(jTable1.getValueAt(rIndex, 0).toString());
//                labelTieuDe.setText(jTable1.getValueAt(rIndex, 1).toString());
//                txtNoiDung.setText(jTable1.getValueAt(rIndex, 2).toString());
//            }
//        });
    }//GEN-LAST:event_formWindowActivated

    private void btnReadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnReadActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnReadActionPerformed

    private void btnSoanEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSoanEmailActionPerformed
        // TODO add your handling code here:
        Send s = new Send();
        s.setVisible(true);
    }//GEN-LAST:event_btnSoanEmailActionPerformed

    private void itemThoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemThoatActionPerformed
        try {
            // TODO add your handling code here:
            Login.transport1.close();
            Login.session1 = null;
            this.setVisible(false);
            Login lg = new Login();
            lg.setVisible(true);



        } catch (MessagingException ex) {
            Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_itemThoatActionPerformed

    private void labelBackMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelBackMouseClicked
        // TODO add your handling code here:
        jScrollPane1.setVisible(true);
        jPanel2.setVisible(false);
    }//GEN-LAST:event_labelBackMouseClicked

    private void labelForwardMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelForwardMouseClicked
        // TODO add your handling code here:
        jScrollPane1.setVisible(false);
        jPanel2.setVisible(true);
    }//GEN-LAST:event_labelForwardMouseClicked

    private void labelSaveMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelSaveMouseClicked
        // TODO add your handling code here:
        JFileChooser jf = new JFileChooser();
        jf.setSelectedFile(attachedFile);
        jf.setCurrentDirectory(new File("D:\\"));
        //FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");
        //jf.setFileFilter(filter);
        int returnVal = jf.showSaveDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            FileOutputStream out = null;
            InputStream in = null;
            try {
                File ni = jf.getSelectedFile(); // Get file
                in = mp.getBodyPart(1).getInputStream();
                out = new FileOutputStream(ni);
                // write
                BufferedOutputStream bufferedOut = new BufferedOutputStream( // data
                        // to
                        // the
                        // file
                        out);
                int b;
                while ((b = in.read()) != -1) {
                    bufferedOut.write(b);
                }
                bufferedOut.flush(); // do write
                in.close(); // close in
                bufferedOut.close(); // and out streams
            } catch (IOException ex) {
                Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
            } catch (MessagingException ex) {
                Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    out.close();
                } catch (IOException ex) {
                    Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    in.close();
                } catch (IOException ex) {
                    Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }//GEN-LAST:event_labelSaveMouseClicked

    private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed
        try {
            // TODO add your handling code here:
            LoadInbox();
        } catch (IOException ex) {
            Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnRefreshActionPerformed

    private void itemDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemDeleteActionPerformed
        // TODO add your handling code here:
        int i = row;
        if (i != -1) {
            try {
                Message msg = NhanEmail.messages[i];
                msg.setFlag(Flags.Flag.DELETED, true);
                LoadInbox();
            } catch (IOException ex) {
                Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
            } catch (MessagingException ex) {
                Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        row = 0;
    }//GEN-LAST:event_itemDeleteActionPerformed

    private void itemClientRowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemClientRowActionPerformed
        // TODO add your handling code here:
        int i = row;
        if (i != -1) {
            try {

                Message msg = NhanEmail.messages[i];
                msg.setFlag(Flags.Flag.SEEN, true);
                LoadInbox();
            } catch (IOException ex) {
                Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
            } catch (MessagingException ex) {
                Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        row = 0;
    }//GEN-LAST:event_itemClientRowActionPerformed

    private void btnGiaiMaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGiaiMaActionPerformed
        // TODO add your handling code here:
        GiaiMa gm = new GiaiMa();
        gm.setVisible(true);
    }//GEN-LAST:event_btnGiaiMaActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;


                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ManHinhChinh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ManHinhChinh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ManHinhChinh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ManHinhChinh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ManHinhChinh().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGiaiMa;
    private javax.swing.JButton btnRead;
    private javax.swing.JButton btnRefresh;
    private javax.swing.JButton btnSoanEmail;
    private javax.swing.JMenuItem itemClientRow;
    private javax.swing.JMenuItem itemDelete;
    private javax.swing.JMenuItem itemThoat;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    public javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    public static javax.swing.JTable jTable1;
    private javax.swing.JLabel labelBack;
    private javax.swing.JLabel labelForward;
    private javax.swing.JLabel labelNgayGui;
    private javax.swing.JLabel labelNguoiGui;
    private javax.swing.JLabel labelSave;
    private javax.swing.JLabel labelTieuDe;
    private javax.swing.JLabel txtFileName;
    private javax.swing.JTextArea txtNoiDung;
    // End of variables declaration//GEN-END:variables
    //public static JTable jTable2;
//    public void Selection() {
//        ManHinhChinh.jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
//
//            public void valueChanged(ListSelectionEvent event) {
//                try {
//                    // do some actions here, for example
//                    // print first column value from selected row
//                    jScrollPane1.setVisible(false);
//                    jPanel2.setVisible(true);
//
//                    int rIndex = ManHinhChinh.jTable1.getSelectedRow();
//                    Message msgMessage;
//                    msgMessage = NhanEmail.messages[rIndex];
//                    Multipart mp = (Multipart) msgMessage.getContent();
//                    //  Boolean chkFile;
//
////                if( mp.getBodyPart(1).getFileName().isEmpty() )
////                    chkFile = false;
////                else
////                    chkFile = true;
////                    
//                    labelNguoiGui.setText(msgMessage.getFrom().toString());
//                    labelTieuDe.setText(msgMessage.getSubject().toString());
//
//                    txtNoiDung.setText(mp.getBodyPart(0).getContent().toString());
//                    //txtFileName.setText(chkFile==true ? mp.getBodyPart(1).getFileName().toString() : "");
//
//                } catch (IOException ex) {
//                    Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
//                } catch (MessagingException ex) {
//                    Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
//                }
//            }
//        });
//    }
    public String filename = null;
    public static File attachedFile = null;
    private Message msgMessage = null;
    private Multipart mp = null;
    private static int row = 0;

    private void LoadInbox() throws IOException {
        try {
            NhanEmail nhan = new NhanEmail();
            nhan.readGmail();
            //jTable1 = jTable2;
            ManHinhChinh.jTable1.setFillsViewportHeight(true);
            //jScrollPane1.add((Component)jTable2);                
            ManHinhChinh.jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

                public void valueChanged(ListSelectionEvent event) {
                    try {
                        // do some actions here, for example
                        // print first column value from selected row
                        msgMessage = null;
                        row = ManHinhChinh.jTable1.getSelectedRow();

                        msgMessage = NhanEmail.messages[row];
                        mp = (Multipart) msgMessage.getContent();

                        Address[] a;
                        if ((a = msgMessage.getFrom()) != null) {
                            for (int j = 0; j < a.length; j++) {
                                labelNguoiGui.setText(a[j].toString());
                            }
                        }

                        labelTieuDe.setText(msgMessage.getSubject().toString());

                        Date d = msgMessage.getSentDate();
                        labelNgayGui.setText(d != null ? d.toLocaleString() : "Khong biet");

                        txtNoiDung.setText(mp.getBodyPart(0).getContent().toString());
//                        Key key;
//                        if(msgMessage.isMimeType("doixung")) {
//                            key = (Key) mp.getBodyPart(2).getDataHandler().getOutputStream();
//                        }
                        if (msgMessage.isMimeType("multipart/*")) {
                            filename = mp.getBodyPart(1).getFileName();
                        }

                        if (filename != null) {
                            txtFileName.setText(filename);
                            attachedFile = new File(filename);
                        } else {
                            txtFileName.setText("Khong co file");
                        }

                        jScrollPane1.setVisible(false);
                        jPanel2.setVisible(true);
                        //txtFileName.setText(chkFile==true ? mp.getBodyPart(1).getFileName().toString() : "");
//                        if(!msgMessage.isMimeType("multipart/*")){
//                            File f = new File(filename);
//                            if(f.exists())
//                            saveFile(f);
//                        }
                    } catch (IOException ex) {
                        Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (MessagingException ex) {
                        Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });

            jPanel2.setVisible(false);
            jScrollPane1.setVisible(true);
        } catch (NoSuchProviderException ex) {
            Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            Logger.getLogger(ManHinhChinh.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void dumpPart(Part p) {
        if (p instanceof Message) {
            Message m = (Message) p;
            Address[] a;
//                        if ((a = msgMessage.getFrom()) != null) {
//                            for (int j = 0; j < a.length; j++) {
//                                labelNguoiGui.setText(a[j].toString());
//                            }
//                        }
        }
    }
}
